package com.fz.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fz.entity.Category;
import com.fz.entity.Goods;
import com.fz.mapper.GoodsMapper;
import com.fz.service.CategoryService;
import com.fz.service.GoodsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fz.service.UploadfileService;
import io.minio.errors.*;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 存储商户提交的商品信息 服务实现类
 * </p>
 *
 * @author hyr
 * @since 2025-06-18
 */
@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements GoodsService {
    @Resource
    UploadfileService uploadfileService;
    @Resource
    GoodsMapper goodsMapper;
    @Resource
    CategoryService categoryService;

    // 添加商品
    @Override
    public Boolean add(String name, String description, BigDecimal price, Integer store, Long categoryId, MultipartFile[] files) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        Goods goods = new Goods(name,description,price,store,categoryId);
//        goods.setCreateTime(DateUtil.now());
        goods.setImgs(Uploadfile(files));
        return this.save(goods);
    }
    //修改商品
    @Override
    public Boolean update(Long id, String name, String description, BigDecimal price, Integer store, Long categoryId, MultipartFile[] files, String[] urls) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        Goods goods = new Goods(id,name,description,price,store,categoryId);
        StringBuffer sb = new StringBuffer();
        StringBuffer originalSb = new StringBuffer(sb);
        //只能用files.length != 0来判断空值

        if(files.length != 0) {//上传新文件时
            //看后面还有没有路径
            if(null != urls && urls.length != 0) {
                sb.append(Uploadfile(files)).append(";");
            }else {
                sb.append(Uploadfile(files));
            }
        }
        if (urls != null && urls.length != 0) {
            sb.append(getPath(urls));
        }
        // 检查sb是否被修改过，如果被修改过，则设置imgs
        if (!originalSb.toString().equals(sb.toString())) {
            goods.setImgs(sb.toString());
        }
        return this.updateById(goods);
    }
    // 存储图片返回路径
    public String Uploadfile(MultipartFile[] files) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        if(null != files) {
            // 添加需要用StringBuffer
            StringBuilder paths = new StringBuilder();
            for(int i = 0; i < files.length; i++) {
                //利用 ; 来分割每一个图片
                if(i != files.length - 1) {
                    paths.append(uploadfileService.upload("goodsimages", files[i])).append(";");
                }else {
                    paths.append(uploadfileService.upload("goodsimages", files[i]));
                }
            }
            return paths.toString();
        }
        return null;
    }
    // 分解商品路径 获取最后的存储路径
    public String getPath(String[] strings) {
        StringBuffer sb = new StringBuffer();
        for(int i = 0; i < strings.length; i++) {
            if(i != strings.length - 1) {
                sb.append(strings[i].substring(strings[i].lastIndexOf('/', strings[i].lastIndexOf('/') - 1))).append(";");
            }
            else {
                sb.append(strings[i].substring(strings[i].lastIndexOf('/', strings[i].lastIndexOf('/') - 1)));
            }
        }
        return sb.toString();
    }
    // 分页查询商品
    @Override
    public IPage<Goods> getList(Integer pageNo, Integer pageSize) {
        IPage<Goods> goodsPage = this.page(new Page<>(pageNo, pageSize));
        List<Goods> goodsList = goodsPage.getRecords();
        splitImagePath(goodsList);
        goodsPage.setRecords(goodsList);
        return goodsPage;
    }
    //按id查询商品
    @Override
    public Goods getById(Long id) {
        Goods goods = super.getById(id);
        List<Goods> goodsList = new ArrayList<>();
        goodsList.add(goods);
        splitImagePath(goodsList);
        return goods;
    }
    // 按类别查询商品
    @Override
    public IPage<Goods> getByCategoryId(Long categoryId, Integer pageNo, Integer pageSize) {
        if(categoryId != -1L){//按类别查询
            QueryWrapper<Goods> wrapper = new QueryWrapper<>();
            wrapper.eq("category_id", categoryId);
            Page<Goods> goodsPage = this.page(( new Page<>(pageNo, pageSize)), wrapper);
            splitImagePath(goodsPage.getRecords());
            return goodsPage;
        }
        Page<Goods> goodsPage = this.page(new Page<>(pageNo, pageSize));
        splitImagePath(goodsPage.getRecords());
        return goodsPage;
    }
    // 按类别查询商品
    @Override
    public IPage<Goods> getHotList( Integer pageNo, Integer pageSize) {
        //按类别查询
        QueryWrapper<Goods> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("sales");
        Page<Goods> goodsPage = this.page((                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            new Page<>(pageNo, pageSize)), wrapper);
        splitImagePath(goodsPage.getRecords());
        return goodsPage;
    }
    // 获取推荐商品
    @Override
    public List<Goods> getMarketingGoods(Long marketingId) {
        List<Goods> marketingGoods = goodsMapper.getMarketingGoods(marketingId);
        splitImagePath(marketingGoods);
        return marketingGoods;
    }
    // 获取热销商品
    @Override
    public List<Goods> getHotSalesGoods() {
        QueryWrapper<Goods> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("sales"); // 按销量降序排序
        List<Goods> goodsList = this.list(wrapper);
        splitImagePath(goodsList);
        return goodsList;
    }
    // 在类别和价格两个条件下 查询商品
    @Override
    public IPage<Goods> getByPriceOrderAndCategory(Long categoryId, Integer order, BigDecimal maxPrice, BigDecimal minPrice, Integer pageNo, Integer pageSize) {
        // order:true为降序 false为升序
        // 0为按销量降序 1为按价格升序  2为按价格降序
        QueryWrapper<Goods> wrapper = new QueryWrapper<>();
        if(null != maxPrice && null != minPrice) {
            wrapper.between("price", minPrice, maxPrice);
        }
        // 按类别查询
        if(categoryId != -1) {
            List<Category> categoryList = categoryService.findAllLeafNodes(categoryId);
            ArrayList<Long> categoryIds = new ArrayList<>();
            for (Category category : categoryList) {
                categoryIds.add(category.getId());
            }
            wrapper.in("category_id", categoryIds);
            setWrapperOrder(wrapper, order);
        }else {//查全部
            setWrapperOrder(wrapper, order);
        }
        Page<Goods> goodsPage = this.page(new Page<>(pageNo, pageSize), wrapper);
        splitImagePath(goodsPage.getRecords());
        return goodsPage;

    }
    //通过商品名称查询商品
    @Override
    public IPage<Goods> searchByGoodsName(String searchValue, Integer pageNo, Integer pageSize) {
        QueryWrapper<Goods> wrapper = new QueryWrapper<>();
        wrapper.like("name", searchValue);
        Page<Goods> goodsPage = this.page(new Page<>(pageNo, pageSize), wrapper);
        splitImagePath(goodsPage.getRecords());
        return goodsPage;
    }
    // 设置顺序查找
    private void setWrapperOrder(QueryWrapper<Goods> wrapper, Integer order) {
        switch (order){
            // 销量降序
            case 0:
                wrapper.orderByDesc("sales");
                break;
            case 1://价格升序
                wrapper.orderByAsc("price");
                break;
            case 2:
                wrapper.orderByDesc("price");
                break;
            default:
                break;
        }
    }
    // 循环给每一个goods分割图片路径
    public void splitImagePath(List<Goods> goodsList) {
        for(Goods goods : goodsList) {
            String[] pathList = goods.getImgs().split(";");
            goods.setImagePathList(pathList);
        }
    }

    @Override
    public List<Goods> list() {
        List<Goods> list = super.list();
        splitImagePath(list);
        return list;
    }
}
